import { showMessage } from '@/components/antd-comp/message'

import MarkdownViewer from '@/components/file-preview/markdown'
import OfficePreview from '@/components/file-preview/office'
import PictureViewer from '@/components/file-preview/picture'
import TextFileViewer from '@/components/file-preview/text/index'
import { locationContext } from '@/contexts/locationContext'
import { useBuriedEvent } from '@/util/buried'
import { LoadingOutlined } from '@ant-design/icons'
import { useContext, useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import * as streamSaver from 'streamsaver'
import { FileInfoType } from '../constants'
import '../css/preview.less'

const getFileName = url => {
  const parsedUrl = new URL(url)
  const pathParts = parsedUrl.pathname.split('/')
  return pathParts[pathParts.length - 1].replace(/\/$/, '')
}

const downloadFile = async (fileUrl, downloadName, setIsDownload) => {
  console.log('fileUrl, downloadName, setIsDownload', fileUrl, downloadName, setIsDownload)
  setIsDownload(true)
  // 走后端
  // const response = await fetch(`/api/v1/knowledge/download?file_path=${fileUrl}`)
  // 直接走sso
  const response = await fetch(fileUrl)
  try {
    console.log('开始文件下载失败', response)
    // 检查HTTP状态码是否在200-299之间
    if (!response.ok) {
      showMessage({
        content: `${response.status} 文件下载失败`,
        type: 'error'
      })
      return
    }
    const fileStream = streamSaver.createWriteStream(downloadName)
    const writer = fileStream.getWriter()

    const reader = response.body.getReader()
    const pump = () =>
      reader.read().then(({ value, done }) => {
        if (done) writer.close()
        else {
          writer.write(value)
          return writer.ready.then(pump)
        }
      })

    await pump()
      .then(() => {
        console.log('Closed the stream, Done writing')
        setTimeout(() => {
          setIsDownload(false)
        }, 1000)
      })
      .catch(err => console.log(err))
  } catch (error) {
    showMessage({
      content: error,
      type: 'error'
    })
    setTimeout(() => {
      setIsDownload(false)
    }, 1000)
  }
}
/**
 * 文档预览入口
 */
interface PreviewPageProps {
  fileInfo: FileInfoType
  open?: boolean
  setOpen: (status: boolean) => void
}

const officeTypes = ['doc', 'docx', 'pdf', 'xls', 'xlsx', 'csv', 'ppt', 'pptx']
const textTypes = ['txt', 'log', 'json']
const pictureTypes = ['png', 'jpg', 'jpeg']
const markdownTypes = ['md']

const PreviewPage = ({ fileInfo, setOpen }: PreviewPageProps) => {
  const { id } = useParams()
  const { appConfig } = useContext(locationContext)
  const [loading, setLoading] = useState(true)
  const [loadError, setLoadError] = useState(false)
  const [filetype, setFileType] = useState('txt')
  const [renderedComponent, setRenderedComponent] = useState(<></>)
  const handleError = msg => {
    showMessage({
      content: msg || '文件加载失败',
      type: 'error'
    })
    setLoading(false)
    setLoadError(true)
  }

  // ESC退出
  useEffect(() => {
    const handleEscKey = event => {
      if (event.key === 'Escape') {
        console.log('Escape key was pressed!')
        setOpen(false)
      }
    }
    window.addEventListener('keydown', handleEscKey)
    return () => {
      window.removeEventListener('keydown', handleEscKey)
    }
  }, [])

  useEffect(() => {
    const type = fileInfo?.file_name ? fileInfo.file_name.slice(fileInfo.file_name.lastIndexOf('.') + 1) : ''
    console.log('PreviewPage type', type)
    let component = <></>
    if (textTypes.includes(type)) {
      component = (
        <div className="text-preview-box">
          <div className="text-preview">
            <TextFileViewer
              configProps={{
                serverUrl: appConfig.officeUrl,
                key: fileInfo.file_name,
                fileType: type,
                title: fileInfo.file_name,
                fileUrl: fileInfo.file_path
                // fileUrl: getFileName(fileInfo.file_path)
              }}
              setLoading={setLoading}
              // downloadFile={() => downloadFile(getFileName(fileInfo.file_path), fileInfo.file_name, setIsDownload)}
              // minio迁移到sso
              downloadFile={() => downloadFile(fileInfo.file_path, fileInfo.file_name, setIsDownload)}
              handleError={handleError}
            />
          </div>
        </div>
      )
    } else if (pictureTypes.includes(type)) {
      component = (
        <div className="picture-preview">
          <PictureViewer
            configProps={{
              serverUrl: appConfig.officeUrl,
              key: fileInfo.file_name,
              fileType: type,
              title: fileInfo.file_name,
              fileUrl: fileInfo.file_path
              // fileUrl: getFileName(fileInfo.file_path)
            }}
            setLoading={setLoading}
            handleError={handleError}
          />
        </div>
      )
    } else if (markdownTypes.includes(type)) {
      component = (
        <div className="text-preview-box">
          <div className="text-preview">
            <MarkdownViewer
              configProps={{
                serverUrl: appConfig.officeUrl,
                key: fileInfo.file_name,
                fileType: type,
                title: fileInfo.file_name,
                fileUrl: fileInfo.file_path
                // fileUrl: getFileName(fileInfo.file_path)
              }}
              setLoading={setLoading}
              // downloadFile={() => downloadFile(getFileName(fileInfo.file_path), fileInfo.file_name, setIsDownload)}
              downloadFile={() => downloadFile(fileInfo.file_path, fileInfo.file_name, setIsDownload)}
              handleError={handleError}
            />
          </div>
        </div>
      )
    } else if (officeTypes.includes(type)) {
      component = (
        <div className="office-preview">
          <OfficePreview
            configProps={{
              serverUrl: appConfig.officeUrl,
              key: getFileName(fileInfo.file_path),
              fileType: type,
              title: getFileName(fileInfo.file_path),
              fileUrl: fileInfo.file_path
            }}
            setLoading={setLoading}
            handleError={handleError}
          />
        </div>
      )
    } else {
      component = (
        <div className="text-preview-box">
          <div className="min-h-[calc(100vh-144px)]">尚为支持的文件类型</div>
        </div>
      )
    }
    setRenderedComponent(component)
    setFileType(type)
  }, [fileInfo])

  const [isDownload, setIsDownload] = useState(false)
  const { fileLibBuriedEvent } = useBuriedEvent()

  return (
    <div className="migu-file-preview">
      <div className="top-preview">
        <div className="title">{fileInfo.file_name}</div>
        <div className="buttons">
          {isDownload ? (
            <LoadingOutlined style={{ color: 'white', width: '18px', height: '18px' }} />
          ) : (
            <span
              className="cursor-pointer"
              onClick={() => {
                fileLibBuriedEvent({
                  page: '文件预览页面',
                  event_name: '【下载】按钮',
                  data_id: id
                })
                // downloadFile(getFileName(fileInfo.file_path), fileInfo.file_name, setIsDownload)
                // minio迁移到sso
                downloadFile(fileInfo.file_path, fileInfo.file_name, setIsDownload)
              }}
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32" fill="none">
                <path d="M16 9L16 19" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                <path
                  d="M11 14L16 19L21 14"
                  stroke="white"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
                <path d="M10 23H22" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </span>
          )}

          <span
            className="cursor-pointer"
            onClick={() => {
              fileLibBuriedEvent({
                page: '文件预览页面',
                event_name: '【关闭】按钮',
                data_id: id
              })
              setOpen(false)
            }}
          >
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M3 3L13 13" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              <path d="M3 13L13 3" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </span>
        </div>
      </div>
      {!loading && !loadError && officeTypes.includes(filetype) && (
        <div
          className="office-left-mask"
          style={{ backgroundColor: ['csv', 'xls', 'xlsx'].includes(filetype) ? '#333333' : '#555555' }}
        ></div>
      )}

      {loading && (
        <div className="absolute left-0 top-0 z-10 flex h-full w-full items-center justify-center bg-[rgba(255,255,255,1)] dark:bg-blur-shared">
          <span className="loading loading-infinity loading-lg"></span>
        </div>
      )}
      {!loadError && renderedComponent}
    </div>
  )
}

export default PreviewPage
